package com.zlm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 郑
 */
@Service
public class RedisService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public void hello(){

        String token = UUID.randomUUID().toString();
        //如果没有就设置值和超时时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token, 3, TimeUnit.SECONDS);
        if (lock) {
            String num = redisTemplate.opsForValue().get("num");
            if(num != null){
                Integer i = Integer.parseInt(num);
                i = i + 1;
                redisTemplate.opsForValue().set("num",i.toString());
            }else{
                redisTemplate.opsForValue().set("num","0");
            }

            redisTemplate.delete("lock");
            //删锁 使用lua脚本
            String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) " +
                    "else return 0 end";
            DefaultRedisScript defaultRedisScript = new DefaultRedisScript();
            defaultRedisScript.setResultType(String.class);
            defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("demo.lua")));
            redisTemplate.execute(defaultRedisScript, Arrays.asList("lock"),token);
            System.out.println("删锁成功...");

        }else{
            hello();
        }

    }


}
